# 操作MySQL
# pip install pymysql
import pymysql

# 创建连接
conn = pymysql.connect(user='root', passwd='123456', host='master', port=3306, database='student')

# 创建游标 类似statement
cursor = conn.cursor()
# 返回最后查询出来的条数
t = cursor.execute("select id,name,age from student where clazz like %s and gender=%s", ('理科%', '男'))
print("总计记录数：", t)
# print(cursor.fetchone())  # 返回一条记录
# print(cursor.fetchmany(3))  # 返回n条记录
# print(cursor.fetchall())  # 返回所有记录 注意使用

# 循环打印
for i in range(t):
    print(cursor.fetchone())
# 关闭连接
cursor.close()
conn.close()

with pymysql.connect(user='root', passwd='123456', host='master', port=3306, database='student') as conn:
    with conn.cursor() as cursor:
        nums = cursor.execute("select * from student where age>%s", 23)
        for i in range(nums):
            print(cursor.fetchone())
        # conn.rollback() # 发生错误进行回滚
        # conn.commit() # 没有异常直接提交